<?php
/**
 * FileUpload.class.php
 * Created on Jun 20, 2007
 * Created by panhuilin<woxuelangzi@yahoo.com.cn>
 * 
 * @function This class is used to deal with file upload.
 */
class FileUpload {

    private $allowExt;
    public  $errMsg;
    private $sucMsg;
    private $upInfo;
    private $savePath;
    private $fileExt = "";
    private $fileSize;
    private $fSaveName="";
    
    function FileUpload( $fInputName, $allowExt, $savePath, $fileSize = 2048000 ) {
    	
    	if( !empty( $fInputName ) && !empty( $allowExt ) && !empty( $savePath ) ){
    		$this->upInfo = $_FILES[$fInputName];
    		$this->allowExt = $allowExt;
    		$this->savePath = $savePath;
    		$this->fileSize = $fileSize;
    		
    		if( $this->checkUploadErr() && $this->checkType() && $this->checkSize() ){
    			
    			$this->renameFile();
    			$this->fSaveName = basename( $this->savePath );
    			$this->saveFile();
    		}
    		$this->setSessMsg();
    	}
    }
    public function getFSaveName(){
    	return $this->fSaveName;
    }
    public function checkUploadErr(){
    	
    	if( empty( $this->upInfo ) ){
    		$this->errMsg = "文件域表单控件名出错";
    		return false;
    	}
    	if( $this->upInfo['error'] > 0 ){
    		switch( $this->upInfo['error'] ){
    			case 1: $this->errMsg = "超过最大文件长度!"; break;
    			case 2: $this->errMsg = "超过文件最大限制!"; break;
    			case 3: $this->errMsg = "文件只被部分上传!"; break;
    			case 4: $this->errMsg = "没有文件上传!";
    		}
    		return false;
    	}
    	else{
    		return true;
    	}
    }
    
    public function checkSize(){
    	
    	if( $this->upInfo['size'] > $this->fileSize ){
    		$this->errMsg = "上传文件超过指定大小";
    		return false;
    	}
    	else return true;
    }
    
    public function checkType(){
    	
    	$arrLen = count( $this->allowExt );
    	for( $i = 0 ; $i < $arrLen; $i++ ){
    		
    		if( stristr( $this->upInfo['name'],$this->allowExt[$i] ) ){
    			$this->fileExt = $this->allowExt[$i];
    			return true;
    		}
    	}
    	$this->errMsg = "无法上传此类型文件";
    	return false;
    }
    
    public function renameFile(){
    	
    	$newName = time().rand( 10000, 99999 );
    	$this->savePath = $this->savePath. "/" . $newName . "." . $this->fileExt;
    }
    
    public function saveFile(){
    	
    	if( is_uploaded_file( $this->upInfo['tmp_name']) ){
    		
    		move_uploaded_file( $this->upInfo['tmp_name'], $this->savePath );
    		$this->sucMsg = "文件上传成功!";
    		return true;
    	}
    	else{
    		
    	    $this->errMsg = "文件上传失败";
    		return false;
    	}
    }
    
    public function setSessMsg(){
    	if (!isset($_SESSION)) session_start();
    	$_SESSION["uploadErrMsg"] = $this->errMsg;
    }
    
    public function getErrMsg(){
    	return $this->errMsg;
    }
    
    public function getSucMsg(){
    	return $this->SucMsg;
    }
    
    public function getFSavePath(){
    	return $this->savePath;
    }
}
?>